package com.qbw.app.module.common.util;

import android.text.TextUtils;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.google.gson.Gson;
import com.http.okhttp.HttpTask;
import com.lib.util.StringUtil;
import com.qbw.app.manager.GeneralManager;
import com.qbw.app.model.Address;
import com.qbw.app.model.BaiduAddress;
import com.qbw.app.request.impl.CommonRequest;
import com.qbw.core.observable.ObservableString;
import com.qbw.l.L;
import com.qbw.log.XLog;

import java.lang.ref.WeakReference;
import java.util.Random;

/**
 * @author qinbaowei
 * @date 2018/3/11
 * @email qbaowei@qq.com
 */
@Deprecated
public class BaiduUtil implements HttpTask.CallBack {
    private static final String BAIDU_API_FORMAT = "http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=%f,%f&output=json&pois=0&ak=HpGo29OlZr4U65s6zqj5AGfqT7aAGaEy&mcode=62:4C:2E:86:48:4F:99:1D:DA:59:E9:77:50:C2:9D:D3:4A:D3:10:7D;com.ztewelink.zte&coordtype=wgs84ll";

    private static final String BAIDU_API_CHINA_FORMAT = "http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=%f,%f&output=json&pois=0&ak=TFq0TgpE4vYi1O5sTSaQZgUpMOhen8F6&mcode=62:4C:2E:86:48:4F:99:1D:DA:59:E9:77:50:C2:9D:D3:4A:D3:10:7D;com.ztewelink.zte.china&coordtype=wgs84ll";

    private final String KEY_LAT = "key_lat";
    private final String KEY_LON = "key_lon";
    private final String KEY_EXTRA = "key_extra";
    private WeakReference<Callback> mWrCallback;

    public BaiduUtil(Callback callback) {
        mWrCallback = new WeakReference<>(callback);
    }

    private String getApiFormat() {
        return BAIDU_API_FORMAT;
    }

    public void getAddress(final double lat, final double lon, final Object extra) {
        GeneralManager.getInstance()
                      .getRequestManager()
                      .getCommonRequest()
                      .getAddress(String.valueOf(lat), String.valueOf(lon), this)
                      .execute();
    }

    /*public void getAddress(final double lat, final double lon, final Object extra) {
        String url = String.format(getApiFormat(), lat, lon);
        HttpTask.create("", null, BaiduAddress.class, this)
                .setGlobalDeal(false)
                .setNoCommonParam(true)
                .setUrl(url)
                .addExtraParam(KEY_LAT, lat)
                .addExtraParam(KEY_LON, lon)
                .addExtraParam(KEY_EXTRA, extra)
                .get()
                .execute(new HttpTask.IDataConverter() {
                    @Override
                    public Object doConvert(String dataStr, Class responseClass) {
                        if (!TextUtils.isEmpty(dataStr)) {
                            if (*//*Config.isDeveloperChannel()*//*false) {//模拟转换失败
                                Random random = new Random(System.currentTimeMillis());
                                int rv = random.nextInt();
                                if (rv % 9 == 0) {
                                    dataStr = "{\"status\": 240,\"message\": \"APP 服务被禁用\", \"qbw\":\"模拟\" }";
                                }
                            }
                            dataStr = dataStr.substring(dataStr.indexOf("{"),
                                                        dataStr.lastIndexOf("}") + 1);
                            XLog.d(dataStr);
                            try {
                                return new Gson().fromJson(dataStr, responseClass);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        return null;
                    }
                });
    }*/

    public static String getLatLon(double lat, double lon) {
        //return String.format("%f, %f", lat, lon);
        return new StringBuilder().append(lat).append(", ").append(lon).toString();
    }

    public static double getDistance(double lat_a, double lng_a, double lat_b, double lng_b) {//单位 米
        double pk = 180 / 3.14169;
        double a1 = lat_a / pk;
        double a2 = lng_a / pk;
        double b1 = lat_b / pk;
        double b2 = lng_b / pk;
        double t1 = Math.cos(a1) * Math.cos(a2) * Math.cos(b1) * Math.cos(b2);
        double t2 = Math.cos(a1) * Math.sin(a2) * Math.cos(b1) * Math.sin(b2);
        double t3 = Math.sin(a1) * Math.sin(b1);
        double tt = Math.acos(t1 + t2 + t3);
        return 6371000 * tt;
    }

    public static double getKmPerHour(double lat_a,
                                      double lng_a,
                                      double lat_b,
                                      double lng_b,
                                      long time) {
        double km = getDistance(lat_a, lng_a, lat_b, lng_b) / 1000;
        double hour = Math.abs(time) / 1000f / 60 / 60;
        return km / hour;
    }

    public static float getMapZoom(double minLat, double minLon, double maxLat, double maxLon) {
        int[] zoomLevel = new int[]{
                50,
                100,
                200,
                500,
                1000,
                2000,
                5000,
                10000,
                20000,
                25000,
                50000,
                100000,
                200000,
                500000,
                1000000,
                2000000
        };//级别18到3。
        int jl = (int) DistanceUtil.getDistance(new LatLng(maxLat, maxLon),
                                                new LatLng(minLat, minLon));
        int i;
        for (i = 0; i < zoomLevel.length; i++) {
            if (zoomLevel[i] > jl) {
                return 18 - i + 3;//之所以会多3，是因为地图范围常常是比例尺距离的10倍以上。所以级别会增加3。
            }
        }
        return 11;
    }

    @Override
    public void onHttpStart(HttpTask httpTask) {

    }

    @Override
    public void onHttpSuccess(HttpTask httpTask, Object entity) {
        Callback callback = mWrCallback.get();
        if (callback == null) {
            L.GL.w("callback = null");
            return;
        }
        String method = httpTask.getMethod();
        if (method.equals(CommonRequest.METHOD_GET_ADDRESS)) {
            Address address = (Address) entity;
            callback.onGetPointAddress(true, address.getData(), null);
        } else {
            if (entity != null) {
                BaiduAddress address = (BaiduAddress) entity;
                if (address.getResult() != null) {
                    String add = address.getResult().getFormatted_address();
                    boolean success = !TextUtils.isEmpty(add);
                    double lat = (double) httpTask.getExtraParam(KEY_LAT);
                    double lon = (double) httpTask.getExtraParam(KEY_LON);
                    Object extra = httpTask.getExtraParam(KEY_EXTRA);
                    if (!success) {
                        add = getLatLon(lat, lon);
                    }
                    callback.onGetPointAddress(success, add, extra);
                }
            }
        }
    }

    @Override
    public void onHttpFailed(HttpTask httpTask, int errorCode, String message) {
        Callback callback = mWrCallback.get();
        if (callback == null) {
            return;
        }
        String method = httpTask.getMethod();
        if (method.equals(CommonRequest.METHOD_GET_ADDRESS)) {
            String lat = (String) httpTask.getParams().get("lat");
            String lnt = (String) httpTask.getParams().get("lon");
            callback.onGetPointAddress(false,
                                       getLatLon(StringUtil.numberDouble(lat),
                                                 StringUtil.numberDouble(lnt)),
                                       null);
        } else {
            if (callback != null) {
                double lat = (double) httpTask.getExtraParam(KEY_LAT);
                double lon = (double) httpTask.getExtraParam(KEY_LON);
                Object extra = httpTask.getExtraParam(KEY_EXTRA);
                callback.onGetPointAddress(false, getLatLon(lat, lon), extra);
            }
        }
    }

    public interface Callback {
        void onGetPointAddress(boolean success, String addr, Object extra);
    }
}
